package com.netcracker.educenter.filestorage.servlets.security.authentication;

import com.netcracker.educenter.filestorage.configurator.Configurator;
import com.netcracker.educenter.filestorage.datasource.dao.UserAccess;
import com.netcracker.educenter.filestorage.datasource.dao.user.UserDAO;
import org.apache.log4j.Logger;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(urlPatterns = "/Authentication")
public class AuthenticationServlet extends HttpServlet {

    private static final Logger log = Logger.getLogger(AuthenticationServlet.class);
    private static final String PROTECTED_PAGE = Configurator.getConfigurator().getFileslistPageUrl();
    private static final String LOGIN_PAGE = Configurator.getConfigurator().getLoginPageUrl();

    @Override
    public void service(HttpServletRequest request, HttpServletResponse response) {

        UserAccess userDAO = new UserDAO();
        String userName =  request.getParameter("username");

        String nextPage;

        if (userDAO.userIsLogged(userName, request.getParameter("password"))) {

            nextPage = PROTECTED_PAGE;
            request.getSession().setAttribute("authorized_user", userName);

        } else {
            nextPage = LOGIN_PAGE;
        }

        try {
            response.sendRedirect(request.getContextPath() + nextPage);
        } catch (Exception e) {
            log.error("cannot go to page", e);
        }
    }
}
